
const Drag = (function(){
    function Drag(selector) {
        // 放在构造函数中的属性，都是属于每一个实例单独拥有
        this.elem = selector
        // this.loader = document.getElementById(id)
        this.loader = selector.childNodes[0].childNodes[0]
        console.log(selector, selector.parentNode)

        this.startX = 0;
        this.startY = 0;
        this.sourceX = 0;
        this.sourceY = 0;
    
        this.init();
    }
    
    Drag.prototype = {
        constructor: Drag,
    
        init: function() {
            this.setDrag()
        },
    
        getStyle: function(style) {
            return document.defaultView.getComputedStyle(this.elem, false)[style]
        },
    
        getPostion: function() {
            let pos = {x: 0, y: 0}
    
            let transformValue = this.getStyle('transform');
            if(transformValue == 'none') {
                this.elem.style['transform'] = 'translate(0, 0)';
            } else {
                var temp = transformValue.match(/-?\d+/g);
                pos = {
                    x: parseInt(temp[4].trim()),
                    y: parseInt(temp[5].trim())
                }
            }
            return pos
        },
    
        setPosition: function(pos) {
            this.elem.style['transform'] = 'translate('+ pos.x +'px, '+ pos.y +'px)'
        },
    
        setDrag: function() {
            const that = this
            this.loader.addEventListener('mousedown', start)
    
            function start(e) {
                let pos = that.getPostion()
    
                that.startX = e.pageX
                that.startY = e.pageY
                that.sourceX = pos.x
                that.sourceY = pos.y
    
                document.addEventListener('mousemove', move)
                document.addEventListener('mouseup', end)

                e.stopPropagation();
            }
    
            function move(e) {
                let currentX = e.pageX,
                    currentY = e.pageY
                
                let distanceX = currentX - that.startX,
                    distanceY = currentY - that.startY
    
                that.setPosition({
                    x: (that.sourceX + distanceX).toFixed(),
                    y: (that.sourceY + distanceY).toFixed()
                })
            }
    
            function end() {
                document.removeEventListener('mousemove', move)
                document.removeEventListener('mouseup', end)
            }
        }
    }
    
    return Drag
})()



export default {
    mounted(el, binding) {
        new Drag(el)
    }
}